package com.ruoyi.project.infobaseproject.controller;

import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MyPageHelper;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.evaluate.infoprojectevaluate.controller.InfoProjectEvaluateController;
import com.ruoyi.evaluate.infoprojectevaluate.domain.InfoProjectEvaluate;
import com.ruoyi.evaluate.infoprojectevaluate.service.IInfoProjectEvaluateService;
import com.ruoyi.monitor.infoprojectmonitor.domain.InfoProjectMonitor;
import com.ruoyi.monitor.infoprojectmonitor.service.IInfoProjectMonitorService;
import com.ruoyi.project.infobaseproject.domain.*;
import com.ruoyi.project.infobaseproject.mapper.InfoBaseProjectTargetStagingMapper;
import com.ruoyi.project.infobaseproject.service.IInfoBaseProjectService;
import com.ruoyi.project.infobaseproject.service.IInfoBaseProjectTargetStagingService;
import com.ruoyi.project.infobaseproject.service.IInfoProjectTargetAdjustService;
import com.ruoyi.project.infobaseproject.vo.HomePVO;
import com.ruoyi.project.infobaseproject.vo.InfoBaseProjectVo;
import com.ruoyi.project.infobaseproject.vo.ProjectReleaseVo;

import com.ruoyi.project.infobaseprojectindex.domain.InfoBaseProjectIndex;
import com.ruoyi.project.infobaseprojectindex.service.IInfoBaseProjectIndexService;
import com.ruoyi.project.infobaseprojectindex.vo.InfoBaseProjectIndexVo;
import com.ruoyi.project.infoprojectbasetype.domain.InfoProjectBaseType;
import com.ruoyi.project.infoprojectbasetype.service.IInfoProjectBaseTypeService;
import com.ruoyi.project.infoprojecttarget.domain.InfoProjectTarget;
import com.ruoyi.project.infoprojecttarget.service.IInfoProjectTargetService;
import com.ruoyi.project.infoprojecttarget.vo.AdjustTargetVo;
import com.ruoyi.project.infoprojecttarget.vo.ExamineProjectVo;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.whole.controller.InfoWholeTargetController;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;

import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 项目库Controller
 * @author ruoyi
 * @date 2022-01-24
 */
@RestController
@RequestMapping("/infoBaseProject/infoBaseProject")
@Api(tags = "项目库")
public class InfoBaseProjectController extends BaseController {
    @Autowired
    private IInfoBaseProjectService infoBaseProjectService;
    @Autowired
    private IInfoBaseProjectIndexService iInfoBaseProjectIndexService;
    @Autowired
    private IInfoProjectTargetService infoProjectTargetService;
    @Autowired
    private IInfoProjectMonitorService iInfoProjectMonitorService;
    @Autowired
    private IInfoProjectEvaluateService iInfoProjectEvaluateService;
    @Resource
    private ISysConfigService iSysConfigService;
    @Autowired
    private ISysDeptService iSysDeptService;
    @Autowired
    private IInfoProjectBaseTypeService iInfoProjectBaseTypeService;

    @Resource
    private IInfoProjectTargetAdjustService iInfoProjectTargetAdjustService;

    @Resource
    private ISysUserService iSysUserService;

    @Resource
    private IInfoBaseProjectTargetStagingService iInfoBaseProjectTargetStagingService;

    @Resource
    private InfoBaseProjectTargetStagingMapper infoBaseProjectTargetStagingMapper;

    /**
     * 项目列表查询 包含子项目
     *
     * @param infoBaseProject
     * @return
     */
    @PreAuthorize("@ss.hasPermi('infoBaseProject:infoBaseProject:list')")
    @GetMapping("/infoBaseProjects")
    @ApiOperation("项目列表查询")
    @ApiImplicitParam(name = "infoBaseProject", value = "实体类", dataType = "InfoBaseProject")
    public TableDataInfo infoBaseProjects(InfoBaseProject infoBaseProject) {
        String time = DateUtils.getTime();
        List<InfoBaseProjectVo> infoBaseProjectVos = new ArrayList<>();
        startPage();
        //判断有没有查询所有项目的权限
        //项目库数据以权限划分  有查询所有项目的权限 查询所有  没有该权限的 就根据当前登录用户的 单位 进行查询
        //当前用户权限
        //*:*:* 管理员权限
        List<InfoBaseProject> list = new ArrayList<>();
        Set<String> permissions = SecurityUtils.getLoginUser().getPermissions();
        if (permissions.contains("infoBaseProject:infoBaseProject:allProject") || permissions.contains("*:*:*")) {
            infoBaseProject.setDepartmentId(null);
            list = infoBaseProjectService.selectInfoBaseProjectList(infoBaseProject);
        } else {
            //获取当前单位ID deptId
            Long deptId = SecurityUtils.getDeptId();
            infoBaseProject.setDepartmentId(deptId);
            //只查询部门id等于当前用户的部门id
//            list = infoBaseProjectService.selectInfoBaseProjects(infoBaseProject);
            list = infoBaseProjectService.selectInfoBaseProjectListByDepartmentId(infoBaseProject);
        }
        for (InfoBaseProject baseProject : list) {
            InfoBaseProjectVo infoBaseProjectVo = new InfoBaseProjectVo();
            BeanUtils.copyProperties(baseProject, infoBaseProjectVo);
            //查询子项目
            InfoBaseProject parentProject = new InfoBaseProject();
            parentProject.setParentId(baseProject.getId());
            List<InfoBaseProject> childProjects = infoBaseProjectService.selectInfoBaseChildProjectList(parentProject);
            if (!childProjects.isEmpty()) {
                infoBaseProjectVo.setChildProjects(childProjects);
            }
            infoBaseProjectVos.add(infoBaseProjectVo);
        }
        TableDataInfo dataTable = getDataTable(list);
        dataTable.setRows(infoBaseProjectVos);
        String time1 = DateUtils.getTime();
        System.out.println(time + "=======" + time1);
        return dataTable;
    }

    /**
     * 项目库项目列表查询（审计处是一级项目列表，其他角色是二级项目列表）
     *
     * @param infoBaseProject
     * @return
     */
    @PreAuthorize("@ss.hasPermi('infoBaseProject:infoBaseProject:list')")
    @GetMapping("/infoBaseProjectList")
    @ApiOperation("新版项目列表查询")
    @ApiImplicitParam(name = "infoBaseProjectList", value = "实体类", dataType = "InfoBaseProject")
    public TableDataInfo infoBaseProjectList(InfoBaseProject infoBaseProject) {
        //判断有没有查询所有项目的权限
        //项目库数据以权限划分  有查询所有项目的权限 查询所有  没有该权限的 就根据当前登录用户的 单位 进行查询
        //当前用户权限
        //*:*:* 管理员权限
        List<InfoBaseProject> list = new ArrayList<>();
        Set<String> permissions = SecurityUtils.getLoginUser().getPermissions();
        if (permissions.contains("infoBaseProject:infoBaseProject:allProject") || permissions.contains("*:*:*")||"1".equals(infoBaseProject.getIsLookAll())) {
            infoBaseProject.setDepartmentId(null);
            startPage();
            list = infoBaseProjectService.selectInfoBaseProjectList(infoBaseProject);
        } else {
            //获取当前单位ID deptId
            Long deptId = SecurityUtils.getDeptId();
            infoBaseProject.setDepartmentId(deptId);
            //只查询部门id等于当前用户的部门id
//            list = infoBaseProjectService.selectInfoBaseProjects(infoBaseProject);
            startPage();
            list = infoBaseProjectService.selectInfoBaseProjectListByDepartmentId(infoBaseProject);
        }
        return getDataTable(list);
    }

    /**
     * 项目库项目列表查询（审计处二级项目）
     *
     * @param jsonObject
     * @return
     */
    @PostMapping("/secondInfoProjectList")
    @ApiOperation("新版项目列表查询")
    public AjaxResult secondInfoProjectList(@RequestBody JSONObject jsonObject) {
        BigInteger projectId = jsonObject.getBigInteger("projectId");
        Optional.ofNullable(projectId).orElseThrow(() -> new RuntimeException("项目Id不能为空！"));
        return AjaxResult.success(infoBaseProjectService.getSecondProjectList(projectId));
    }

    /**
     * 项目库项目列表查询（审计处二级项目根据部门查询）
     *
     * @param jsonObject
     * @return
     *
     */
    @PostMapping("/projectDepartmentList")
    @ApiOperation("新版项目列表查询")
    public AjaxResult projectDepartmentList(@RequestBody JSONObject jsonObject) {
        BigInteger parentId = jsonObject.getBigInteger("parentId");
        Optional.ofNullable(parentId).orElseThrow(() -> new RuntimeException("项目Id不能为空！"));
        String projectName = jsonObject.getString("projectName");
        Optional.ofNullable(projectName).orElseThrow(() -> new RuntimeException("项目名称不能为空！"));
        return AjaxResult.success(infoBaseProjectService.getProjectDepartmentList(parentId, projectName));
    }
    /**
     * 查询项目库列表
     */
    @PreAuthorize("@ss.hasPermi('infoBaseProject:infoBaseProject:list')")
    @GetMapping("/list")
    public TableDataInfo list(InfoBaseProject infoBaseProject) {
        startPage();
        List<InfoBaseProject> list = infoBaseProjectService.selectInfoBaseProjectList(infoBaseProject);
        return getDataTable(list);
    }

    /**
     * 导出项目库列表
     */
    //@PreAuthorize("@ss.hasPermi('infoBaseProject:infoBaseProject:export')")
    @Log(title = "项目库", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, InfoBaseProject infoBaseProject) {
        List<InfoBaseProject> list = infoBaseProjectService.selectInfoBaseProjectList(infoBaseProject);
        List<InfoBaseProject> collect = list.stream().filter(x ->"3".equals(x.getProjectStstus())).collect(Collectors.toList());
        for (InfoBaseProject baseProject : collect) {
            baseProject.setDepartmentName(iSysDeptService.selectDeptById(baseProject.getDepartmentId()).getDeptName());
            baseProject.setWorkCompanyName(iSysDeptService.selectDeptById(Long.valueOf(baseProject.getWorkCompany())).getDeptName());
            baseProject.setProjectTypeName(iInfoProjectBaseTypeService.selectInfoProjectBaseTypeById(Long.valueOf(baseProject.getProjectNode())).getName());
        }
        ExcelUtil<InfoBaseProject> util = new ExcelUtil<InfoBaseProject>(InfoBaseProject.class);
        util.exportExcel(response, collect, "项目库数据");
    }

    /**
     * 获取项目库详细信息
     */
    @PreAuthorize("@ss.hasPermi('infoBaseProject:infoBaseProject:query')")
    @GetMapping(value = "/{id}/{type}")
    public AjaxResult getInfo(@PathVariable("id") Long id,@PathVariable("type") String type) {
        if ("3".equals(type)){
            InfoBaseProjectTargetStaging infoBaseProjectTargetStaging = infoBaseProjectTargetStagingMapper.selectInfoBaseProjectTargetStagingByProjectId2(id);
            SysDept sysDept = iSysDeptService.selectDeptById(Long.valueOf(infoBaseProjectTargetStaging.getWorkCompany()));
            infoBaseProjectTargetStaging.setWorkCompanyName(sysDept.getDeptName());
            String deptName = iSysDeptService.selectDeptById(infoBaseProjectTargetStaging.getDepartmentId()).getDeptName();
            infoBaseProjectTargetStaging.setDepartmentName(deptName);
            String name = iInfoProjectBaseTypeService.selectInfoProjectBaseTypeById(Long.valueOf(infoBaseProjectTargetStaging.getProjectNode())).getName();
            infoBaseProjectTargetStaging.setProjectTypeName(name);
            return AjaxResult.success(infoBaseProjectTargetStaging);
        }
        InfoBaseProject infoBaseProject = infoBaseProjectService.selectInfoBaseProjectById(id);
        return AjaxResult.success(infoBaseProject);
    }

    /**
     * 新增项目库
     */
    @PreAuthorize("@ss.hasPermi('infoBaseProject:infoBaseProject:add')")
    @Log(title = "项目库", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody InfoBaseProject infoBaseProject) {
        int i = infoBaseProjectService.insertInfoBaseProject(infoBaseProject);
        AjaxResult result = toAjax(i);
        result.put("projectId", infoBaseProject.getId());
        return result;
    }

    /**
     * 新增项目库(新）
     */
    @Log(title = "项目库", businessType = BusinessType.INSERT)
    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    @ApiOperation("新增项目库")
    @ApiImplicitParam(name = "projectVo", value = "实体类", dataType = "ProjectVo")
    public AjaxResult insert(@RequestBody ProjectVo projectVo) {
        return toAjax(infoBaseProjectService.insertInfoBaseProjects(projectVo));
    }

    /**
     * 修改新（添加指标体系）二级项目修改
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ApiOperation("修改新")
    @ApiImplicitParam(name = "infoBaseProjectIndexVo", value = "实体类", dataType = "InfoBaseProjectIndexVo")
    public AjaxResult update(@RequestBody InfoBaseProjectIndexVo infoBaseProjectIndexVo) {
        return toAjax(iInfoBaseProjectIndexService.batchInsertBaseProjectIndex(infoBaseProjectIndexVo));
    }


    /**
     * 修改项目库
     */
    @PreAuthorize("@ss.hasPermi('infoBaseProject:infoBaseProject:edit')")
    @Log(title = "项目库", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody InfoBaseProject infoBaseProject) {
        return toAjax(infoBaseProjectService.updateInfoBaseProject(infoBaseProject));
    }

    /**
     * 删除项目库
     */
    @PreAuthorize("@ss.hasPermi('infoBaseProject:infoBaseProject:remove')")
    @Log(title = "项目库", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return AjaxResult.success(infoBaseProjectService.deleteInfoBaseProjectByIds(ids));
    }

    /**
     * 项目下达
     *
     * @param projectReleaseVo
     * @return
     */
    @RequestMapping(value = "/projectRelease", method = RequestMethod.POST)
    @PreAuthorize("@ss.hasPermi('infoBaseProject:infoBaseProject:release')")
    public AjaxResult projectRelease(@RequestBody ProjectReleaseVo projectReleaseVo) {
        return toAjax(infoBaseProjectService.projectRelease(projectReleaseVo));
    }

    /**
     * 解析资金文件
     */
    @RequestMapping(value = "/excelImport", method = RequestMethod.POST)
    public TableDataInfo importExcel(MultipartFile file) {
        try {
            List<InfoBaseProject> list = infoBaseProjectService.importExcel(file);
            return getDataTable(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getDataTable(new ArrayList<>());
    }

    /**
     * 分配项目主管处室
     *
     * @param infoBaseProject 参数  id 主键 departmentName 主管处室的名称 departmentId 主管处室的id
     * @return
     */
    @RequestMapping(value = "/assignProject", method = RequestMethod.POST)
    public AjaxResult assignProject(@RequestBody InfoBaseProject infoBaseProject) {
        int i = infoBaseProjectService.updateInfoBaseProject(infoBaseProject);
        return toAjax(i);
    }

    /**
     * 批量分配项目
     *
     * @param jsonObject 参数  id 主键 departmentName 主管处室的名称 departmentId 主管处室的id
     * @return
     */
    @PostMapping("batchAssignProject")
    public AjaxResult batchAssignProject(@RequestBody JSONObject jsonObject) {
        //主管处室id
        Long departmentId = jsonObject.getLong("departmentId");
        Optional.ofNullable(departmentId).orElseThrow(() -> new RuntimeException("主管处室id不能为空！"));
        String departmentName = jsonObject.getString("departmentName");
        Optional.ofNullable(departmentName).orElseThrow(() -> new RuntimeException("主管处室名称不能为空！"));
        //勾选项目id 数组
        JSONArray jsonArray = jsonObject.getJSONArray("id");
        System.out.println("ids----" + JSONObject.toJSONString(jsonArray));

        for (int i = 0; i < jsonArray.size(); i++) {
            InfoBaseProject infoBaseProject = new InfoBaseProject();
            System.out.println("id----" + jsonArray.getLong(i));
            infoBaseProject.setId(jsonArray.getLong(i));
            infoBaseProject.setDepartmentId(departmentId);
            infoBaseProject.setDepartmentName(departmentName);
            infoBaseProjectService.updateInfoBaseProject(infoBaseProject);
        }
        return AjaxResult.success("分配成功！");
    }

    /**
     * 项目评价报告下载
     */
    @PostMapping("/download/{id}")
    @ResponseBody
    @ApiOperation("项目一级评价报告下载所有一级项目")
    public AjaxResult download(@PathVariable("id") Long id) {
        String fileName = null;
        InfoBaseProject infoBaseProjects = infoBaseProjectService.selectInfoBaseProjectById(id);
        //根据项目id查询
        List<InfoBaseProjectIndex> infoBaseProjectIndices = iInfoBaseProjectIndexService.selectInfoBaseProjectIndexByIds(infoBaseProjects.getId());
        try {
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("utf-8");
            String dirPath = InfoProjectEvaluateController.class.getResource("/report/template").getPath();
            configuration.setDirectoryForTemplateLoading(new File(dirPath));
            Template template = configuration.getTemplate("bmss.ftl", "utf-8");
            Map<String, Object> data = new HashMap<>();
            //获取一级下的所有子项目id
            List<InfoBaseProject> infoBaseProjects1 = infoBaseProjectService.selectInfoBaseProjectByIds(id);
            //总额执行数
            BigDecimal totalEx = BigDecimal.ZERO;
            BigDecimal cenEx = BigDecimal.ZERO;
            BigDecimal proEx = BigDecimal.ZERO;
            BigDecimal othEx = new BigDecimal(0);
            for (int i = 0; i < infoBaseProjects1.size(); i++) {
                Long ids = infoBaseProjects1.get(i).getId();

                InfoProjectTarget infoProjectTarget = infoProjectTargetService.selectInfoProjectTargetByIdss(ids);
//                if(infoProjectTarget==null){
//                    throw new RuntimeException("还有子项目未进行自评报告填写！不能生成报告！");
//                }
                if (infoProjectTarget != null) {
                    InfoProjectMonitor infoProjectMonitor = iInfoProjectMonitorService.selectInfoProjectMonitorByIdss(infoProjectTarget.getId());
                    if (infoProjectMonitor != null) {
                        List<InfoProjectEvaluate> infoProjectEvaluate = iInfoProjectEvaluateService.selectInfoProjectEvaluateByIdss(infoProjectMonitor.getId());
                        for (int i1 = 0; i1 < infoProjectEvaluate.size(); i1++) {
                            //获取到他的执行数，执行率
                            InfoProjectEvaluate infoProjectEvaluate1 = infoProjectEvaluate.get(i1);
                            //总额执行数
                            if (!org.springframework.util.StringUtils.isEmpty(infoProjectEvaluate1.getTotalFundsExecute())) {
                                totalEx = totalEx.add(infoProjectEvaluate1.getTotalFundsExecute());
                            }
                            //中央执行数
                            if (!org.springframework.util.StringUtils.isEmpty(infoProjectEvaluate1.getCentralFundExecute())) {
                                cenEx = cenEx.add(infoProjectEvaluate1.getCentralFundExecute());
                            }
                            //省级执行数
                            if (!org.springframework.util.StringUtils.isEmpty(infoProjectEvaluate1.getProvincialFundsExecute())) {
                                proEx = proEx.add(infoProjectEvaluate1.getProvincialFundsExecute());
                            }
                            //其他执行数
                            if (!org.springframework.util.StringUtils.isEmpty(infoProjectEvaluate1.getOtherFundExecute())) {
                                othEx = othEx.add(infoProjectEvaluate1.getOtherFundExecute());
                            }
                        }
                    }
                }
            }
            //计算执行率
            if (!org.springframework.util.StringUtils.isEmpty(infoBaseProjects.getTotalFunds()) && infoBaseProjects.getTotalFunds().compareTo(BigDecimal.ZERO) != 0) {
                BigDecimal totalRa1 = totalEx.divide(infoBaseProjects.getTotalFunds(), 2, BigDecimal.ROUND_HALF_DOWN);
                double totalRa = totalRa1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;
                infoBaseProjects.setTotalRa(String.valueOf(totalRa));
                //得分
                double dfs = totalRa;
                infoBaseProjects.setDf(String.valueOf(dfs));
            } else {
                double totalRa = 0;
                infoBaseProjects.setTotalRa(String.valueOf(totalRa));
                //得分
                double dfs = totalRa;
                infoBaseProjects.setDf(String.valueOf(dfs));
            }

            if (!org.springframework.util.StringUtils.isEmpty(infoBaseProjects.getCentralFund()) && infoBaseProjects.getCentralFund().compareTo(BigDecimal.ZERO) != 0) {
                BigDecimal cenRa1 = cenEx.divide(infoBaseProjects.getCentralFund(), 2, RoundingMode.HALF_UP);
                double cenRa = cenRa1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;
                infoBaseProjects.setCenRa(String.valueOf(cenRa));
            } else {
                double cenRa = 0;
                infoBaseProjects.setCenRa(String.valueOf(cenRa));
            }

            if (!org.springframework.util.StringUtils.isEmpty(infoBaseProjects.getProvincialFunds()) && infoBaseProjects.getProvincialFunds().compareTo(BigDecimal.ZERO) != 0) {
                BigDecimal proRa1 = proEx.divide(infoBaseProjects.getProvincialFunds(), 2, RoundingMode.HALF_UP);
                double proRa = proRa1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;
                infoBaseProjects.setProRa(String.valueOf(proRa));
            } else {
                double proRa = 0;
                infoBaseProjects.setProRa(String.valueOf(proRa));
            }

            if (!org.springframework.util.StringUtils.isEmpty(infoBaseProjects.getOtherFund()) && infoBaseProjects.getOtherFund().compareTo(BigDecimal.ZERO) != 0) {
                BigDecimal othRa1 = othEx.divide(infoBaseProjects.getOtherFund(), 2, RoundingMode.HALF_UP);
                double othRa = othRa1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;
                infoBaseProjects.setOthRa(String.valueOf(othRa));
            } else {
                double othRa = 0;
                infoBaseProjects.setOthRa(String.valueOf(othRa));
            }


            infoBaseProjects.setTotalEx(String.valueOf(totalEx));
            infoBaseProjects.setCenEx(String.valueOf(cenEx));
            infoBaseProjects.setProEx(String.valueOf(proEx));
            infoBaseProjects.setOthEx(String.valueOf(othEx));

            data.put("project", infoBaseProjects);
            //Double fz = 0D;
            Double df = 0D;
            for (int i = 0; i < infoBaseProjectIndices.size(); i++) {
                InfoBaseProjectIndex infoBaseProjectIndex = infoBaseProjectIndices.get(i);

                //if (!org.springframework.util.StringUtils.isEmpty(infoBaseProjectIndex.getTargetValue())) {
                //    fz += Double.parseDouble(infoBaseProjectIndex.getTargetValue());
                //}
                if (!org.springframework.util.StringUtils.isEmpty(infoBaseProjectIndex.getTargetScore())) {
                    df += Double.parseDouble(infoBaseProjectIndex.getTargetScore());
                }
            }
            data.put("projectTargets", infoBaseProjectIndices);

            fileName = infoBaseProjects.getProjectName();
            //data.put("fz", fz);
            data.put("df", df);

            Writer out = null;
            String downloadPath = RuoYiConfig.getDownloadPath() + fileName;
            File desc = new File(downloadPath);
            if (!desc.getParentFile().exists()) {
                desc.getParentFile().mkdirs();
            }
            File outFile = new File(downloadPath + "项目自评价报告" + ".doc");
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
            template.process(data, out);
            out.close();
            System.out.println("................word文档生成成功 !.............");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }


        return AjaxResult.success(fileName + "项目自评价报告" + ".doc");
    }

    /**
     * 部门一级评价报告下载所有一级项目
     */
    @PostMapping("/departmentStatistics")
    @ApiOperation("部门一级评价报告下载所有一级项目")
    public AjaxResult departmentStatistics(Long id) {
        String fileName = null;
        try {
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("utf-8");
            String dirPath = InfoWholeTargetController.class.getResource("/report/template").getPath();
            configuration.setDirectoryForTemplateLoading(new File(dirPath));
            Template template = configuration.getTemplate("bms.ftl", "utf-8");
            /**
             * 把查到的东西放进map中
             */
            Map<String, Object> data = new HashMap<>();
            //查出所有一级项目
            String date = DateUtils.parseDateToStr("yyyy", new Date());
            data.put("year", date);
            /* ----------------------  部门项目汇总开始  ----------------------  */
            List<InfoBaseProject> infoBaseProjects = infoBaseProjectService.selectInfoBaseProject(id, date);
            for (InfoBaseProject infoBaseProject : infoBaseProjects) {
                //获取执行率
                infoBaseProjectService.getInfo(infoBaseProject);
            }
            data.put("projectsInfo", infoBaseProjects);
            /* ----------------------  部门项目汇总结束  ----------------------  */

            String title = date + "年度部门预算支出";
            fileName = title;
            data.put("fileName", title);
            /* ----------------------  项目部分开始  ----------------------  */
            List<ProjectInfoVo> projectInfosList = new LinkedList<>();
            /**
             * 项目整体信息表info_whole_target
             */
            for (int i = 0; i < infoBaseProjects.size(); i++) {
                ProjectInfoVo projectInfoVo = new ProjectInfoVo();
                List<InfoBaseProjectIndex> infoBaseProjectIndices = iInfoBaseProjectIndexService.selectInfoBaseProjectIndexByIds(infoBaseProjects.get(i).getId());
                InfoBaseProject infoBaseProject = infoBaseProjects.get(i);
                //资金总分值及得分
                infoBaseProject.setTotalFz(10 + "");
                infoBaseProject.setTotalDf(10 * (Double.valueOf(infoBaseProject.getTotalRa()) / 100) + "");
                projectInfoVo.setInfoBaseProjects(infoBaseProject);
                Double fz = 0D;
                Double df = 0D;
                if (infoBaseProjectIndices.size() > 0) {
                    for (int j = 0; j < infoBaseProjectIndices.size(); j++) {
                        InfoBaseProjectIndex infoBaseProjectIndex1 = infoBaseProjectIndices.get(j);
                       /* if(!org.springframework.util.StringUtils.isEmpty(infoBaseProjectIndex1.getTargetValue())){
                            fz += Double.parseDouble(infoBaseProjectIndex1.getTargetValue());
                        }*/
                        if (!org.springframework.util.StringUtils.isEmpty(infoBaseProjectIndex1.getTargetScore())) {
                            df += Double.parseDouble(infoBaseProjectIndex1.getTargetScore());
                        }
                    }
                    infoBaseProject.setFz(fz + "");
                    infoBaseProject.setDf(df + "");
                    projectInfoVo.setInfoBaseProjectIndices(infoBaseProjectIndices);
                }
                projectInfosList.add(projectInfoVo);
            }
            data.put("projectInfosList", projectInfosList);

            Writer out = null;

            String downloadPath = RuoYiConfig.getDownloadPath() + fileName;
            File desc = new File(downloadPath);
            if (!desc.getParentFile().exists()) {
                desc.getParentFile().mkdirs();
            }
            File outFile = new File(downloadPath + ".doc");
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
            template.process(data, out);
            out.close();
            System.out.println("................word文档生成成功 !.............");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        return AjaxResult.success(fileName + ".doc");
    }

    /**
     * 统计
     */
    @GetMapping("getTree")
    @ApiOperation("统计省市区")
    public AjaxResult get() {
        return AjaxResult.success(infoBaseProjectService.selectInfoProjects());
    }

    /**
     * 首页统计金额
     */
    @PostMapping("homeStatisticsAmount")
    @ApiOperation("首页统计金额")
    public AjaxResult homeStatisticsAmount(@RequestBody JSONObject jsonObject) {
        Long deptId = jsonObject.getLong("deptId");
        Optional.ofNullable(deptId).orElseThrow(() -> new RuntimeException("省级地区Id不能为空！"));
        return AjaxResult.success(infoBaseProjectService.getHomeStatisticsAmount(deptId));
    }

    /**
     * 项目库资金文件模板下载
     */
    @PostMapping("downloadFundDocument")
    @ApiOperation("项目库资金文件模板下载")
    public AjaxResult downloadFundDocument() {
        String fileAddress = iSysConfigService.selectConfigByKey("FUND_DOCUMENTS");
        File file = new File(fileAddress);
        if (file.exists()) {
            return AjaxResult.success(fileAddress);
        } else {
            return AjaxResult.error("文件不存在！");
        }
    }

    /**
     * 项目库手动添加项目
     */
    @PostMapping("handAddProject")
    @ApiOperation("项目库手动添加项目")
    public AjaxResult handAddProject(@RequestBody InfoBaseProject infoBaseProject) {
        infoBaseProjectService.handAddProject(infoBaseProject);
        return AjaxResult.success("保存成功！！");
    }


    /**
     * ============================================================新增====================================================================
     */
    /**
     * 新增
     * @param infoBaseProject
     * @return
     */
    @PostMapping("/insertProjectTo")
    public AjaxResult insertProjectTo(@RequestBody InfoBaseProject infoBaseProject){
       return toAjax(infoBaseProjectService.insertInfoBaseProject(infoBaseProject));
    }

    /**
     * 列表查
     * @param infoBaseProject
     * @return
     */
    @GetMapping("/findAllPb")
    public AjaxResult findAllPb(InfoBaseProject infoBaseProject){
        return AjaxResult.success(infoBaseProjectService.selectInfoBaseProjectList(infoBaseProject));
    }

    /**
     * 提交
     * 传 id 和 ancestors  选择的上级部门  状态
     * @param infoBaseProject
     * @return
     */
    @PostMapping("/submitProject")
    public AjaxResult submitProject(@RequestBody InfoBaseProject infoBaseProject){
       return AjaxResult.success(infoBaseProjectService.submitProject(infoBaseProject));
    }

    /**
     * 审核
     * 传 id 意见 状态第一次传2 终审传3退回4
     * @param infoBaseProject
     * @return
     */
    @PostMapping("/examineProject")
    public AjaxResult examineProject (@RequestBody InfoBaseProject infoBaseProject){
        return infoBaseProjectService.examineProject(infoBaseProject);
    }

    /**
     * 填报列表
     * @param infoBaseProject
     * @return
     */
    @GetMapping("/tbList")
    public TableDataInfo tbList(InfoBaseProject infoBaseProject){
        List<ProjectInfoVo> projectInfoVos = new ArrayList<>();

        startPage();
        List<InfoBaseProject> infoBaseProjects = infoBaseProjectService.selectInfoBaseProjectsTb(infoBaseProject);
        for (InfoBaseProject baseProject : infoBaseProjects) {
            baseProject.setWorkCompanyName(iSysDeptService.selectDeptById(Long.valueOf(baseProject.getWorkCompany())).getDeptName());
            baseProject.setDepartmentName(iSysDeptService.selectDeptById(baseProject.getDepartmentId()).getDeptName());
            ProjectInfoVo projectInfoVo = new ProjectInfoVo();
            InfoProjectTargetAdjust infoProjectTargetAdjust = new InfoProjectTargetAdjust();
            infoProjectTargetAdjust.setBaseProjectId(baseProject.getId());
            //组装状态
            InfoProjectTargetAdjust infoProjectTargetAdjust1 = iInfoProjectTargetAdjustService.selectInfoProjectTargetAdjustByProjectId(baseProject.getId());
            if (StringUtils.isNotNull(infoProjectTargetAdjust1)){
                if (StringUtils.isNotNull(infoProjectTargetAdjust1.getBaseProjectStagingId())){
                    InfoBaseProjectTargetStaging infoBaseProjectTargetStaging = iInfoBaseProjectTargetStagingService.selectInfoBaseProjectTargetStagingByProjectId(infoProjectTargetAdjust1.getBaseProjectStagingId());
                    infoProjectTargetAdjust1.setProjectAdjustStatus(infoBaseProjectTargetStaging.getProjectAdjustStatus());
                }
                //查目标表   获取目标状态
                if (StringUtils.isNotNull(infoProjectTargetAdjust1.getBaseProjectTargetNewId())){
                    InfoProjectTarget infoProjectTarget = infoProjectTargetService.selectInfoProjectTargetById(infoProjectTargetAdjust1.getBaseProjectTargetNewId());
                    infoProjectTargetAdjust1.setTargetAdjustStatus(infoProjectTarget.getExamineStatus());
                }
            }
            List<InfoProjectTargetAdjust> infoProjectTargetAdjusts = new ArrayList<>();
            infoProjectTargetAdjusts.add(infoProjectTargetAdjust1);
            projectInfoVo.setInfoBaseProjects(baseProject);
            projectInfoVo.setInfoProjectTargetAdjust(infoProjectTargetAdjusts);
            projectInfoVos.add(projectInfoVo);
        }
        TableDataInfo dataTable = getDataTable(infoBaseProjects);
        dataTable.setRows(projectInfoVos);
        //审核通过且项目阶段为0  过滤
        //List<InfoBaseProject> collect = infoBaseProjects.stream().filter(x -> x.getIsXg() == 0 && "3".equals(x.getProjectStstus())).collect(Collectors.toList());
        return dataTable;
    }

    @GetMapping("/shList")
    public TableDataInfo shList(InfoBaseProject infoBaseProject,int pageNum,int pageSize){

        List<ProjectInfoVo> projectInfoVos = new ArrayList<>();


        List<InfoBaseProject> infoBaseProjects = infoBaseProjectService.selectInfoBaseProjectsSh(infoBaseProject);
        for (InfoBaseProject baseProject : infoBaseProjects) {
            ProjectInfoVo projectInfoVo = new ProjectInfoVo();
            InfoProjectTargetAdjust infoProjectTargetAdjust1 = iInfoProjectTargetAdjustService.selectInfoProjectTargetAdjustByProjectId(baseProject.getId());
            if (StringUtils.isNotNull(infoProjectTargetAdjust1)){
                if (StringUtils.isNotNull(infoProjectTargetAdjust1.getBaseProjectStagingId())){
                    InfoBaseProjectTargetStaging infoBaseProjectTargetStaging = iInfoBaseProjectTargetStagingService.selectInfoBaseProjectTargetStagingByProjectId(infoProjectTargetAdjust1.getBaseProjectStagingId());
                    infoProjectTargetAdjust1.setProjectAdjustStatus(infoBaseProjectTargetStaging.getProjectAdjustStatus());
                }
                //查目标表   获取目标状态
                if (StringUtils.isNotNull(infoProjectTargetAdjust1.getBaseProjectTargetNewId())){
                    InfoProjectTarget infoProjectTarget = infoProjectTargetService.selectInfoProjectTargetById(infoProjectTargetAdjust1.getBaseProjectTargetNewId());
                    infoProjectTargetAdjust1.setTargetAdjustStatus(infoProjectTarget.getExamineStatus());
                }
            }
            SysUser sysUser = iSysUserService.selectUserById(SecurityUtils.getUserId());
            List<String> collect = sysUser.getRoles().stream().map(SysRole::getRoleKey).collect(Collectors.toList());
            if (collect.contains("sjc")){
                projectInfoVo.setIsWho(1l);
                if (StringUtils.isNotNull(infoProjectTargetAdjust1)){
                    infoProjectTargetAdjust1.setIsWho(1);
                }
            }
            if (baseProject.getDepartmentId().equals(SecurityUtils.getDeptId())){
                projectInfoVo.setIsWho(0l);
                if (StringUtils.isNotNull(infoProjectTargetAdjust1)){
                    infoProjectTargetAdjust1.setIsWho(0);
                }
            }
            List<InfoProjectTargetAdjust> infoProjectTargetAdjusts = new ArrayList<>();
            infoProjectTargetAdjusts.add(infoProjectTargetAdjust1);
            projectInfoVo.setInfoBaseProjects(baseProject);
            projectInfoVo.setInfoProjectTargetAdjust(infoProjectTargetAdjusts);
            projectInfoVos.add(projectInfoVo);
        }
        //使用工具类对list进行分页
        MyPageHelper pageHelper = new MyPageHelper();
        PageInfo pageInfo = pageHelper.pageHelpList(projectInfoVos, pageNum, pageSize);
        //将分页好的数据封装到tableDataInfo
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setTotal(pageInfo.getTotal());
        tableDataInfo.setRows(pageInfo.getList());
        return tableDataInfo;
    }

    /**
     * 储备项目库列表/年度项目库
     * @param infoBaseProject
     * @return
     */
    @GetMapping("/stockpileList")
    public TableDataInfo stockpileList(InfoBaseProject infoBaseProject){
        infoBaseProject.setProjectStstus("3");
        //1 已实施  0 未实施
        infoBaseProject.setImplementStatus(1);
        startPage();
        List<InfoBaseProject> infoBaseProjects = infoBaseProjectService.selectInfoBaseProjectList(infoBaseProject);
        return getDataTable(infoBaseProjects);
    }

    /**
     * 实施项目  传项目id
     * 在项目审核  实施  实施后的项目进入到年度项目库和目标
     * @return
     */
    @PostMapping("/implementProject")
    public AjaxResult implementProject(@RequestBody InfoBaseProject infoBaseProject){
       return infoBaseProjectService.implementProject(infoBaseProject);
    }
    //下发调整
    @PostMapping("/dstribute")
    public AjaxResult dstribute(@RequestBody InfoBaseProject infoBaseProject){
        infoBaseProject.setIsXg(1);
        return toAjax(infoBaseProjectService.updateInfoBaseProject(infoBaseProject));
    }


    /**
     * 申请调整
     *  选择框
     *  项目调整 1
     *  目标调整 1
     */
    @PostMapping("/applyAdjust")
    public AjaxResult applyAdjust(@RequestBody InfoProjectTargetAdjust infoProjectTargetAdjust){
        return infoBaseProjectService.applyAdjust(infoProjectTargetAdjust);
    }

    /**
     * 申请审核接口
     * @param infoProjectTargetAdjust
     * @return
     */
    @PostMapping("/examineAdjust")
    public AjaxResult examineAdjust(@RequestBody InfoProjectTargetAdjust infoProjectTargetAdjust){

        return infoBaseProjectService.examineAdjust(infoProjectTargetAdjust);
    }

    /**
     * 项目信息调整
     * 项目信息回显接口调原有的项目详情接口即可
     * @param infoBaseProject
     * @return
     */
    @PostMapping("/adjustProject")
    public AjaxResult adjustProject(@RequestBody InfoBaseProject infoBaseProject){
        return infoBaseProjectService.adjustProject(infoBaseProject);
    }

    /**
     * 项目调整审核
     * @param infoBaseProject
     * @return
     */
    @PostMapping("/examineAdjustProject")
    public AjaxResult examineAdjustProject(@RequestBody InfoBaseProject infoBaseProject){
        return infoBaseProjectService.examineAdjustProject(infoBaseProject);
    }


//    /**
//     * 信息回显 调原有详情接口
//     * 目标调整接口  不用 （）
//     * @param adjustTargetVo
//     * @return
//     */
//    @PostMapping("/adjustProjectTarget")
//    public AjaxResult adjustProjectTarget(@RequestBody AdjustTargetVo adjustTargetVo){
//
//        return infoProjectTargetService.adjustProjectTarget(adjustTargetVo);
//    }

    /**
     * 目标审核接口  （不用）
     * @param examineProjectVo
     * @return
     */
    @PostMapping("/examineAdjustTarget")
    public AjaxResult examineAdjustTarget(@RequestBody ExamineProjectVo examineProjectVo){

        return infoProjectTargetService.examineAdjustTarget(examineProjectVo);
    }

    /**
     * =====================首页=========================
     */
    //统计下古墓个数以及贫困村数以及金额
    @ApiOperation("统计下古墓个数以及贫困村数以及金额")
    @GetMapping("/homeSize")
    public AjaxResult homeSize(){
        HomePVO homePVO =  infoBaseProjectService.selectHomePage();
//        BigDecimal totalFund = homePVO.getTotalFund();
//        BigDecimal bigDecimal = totalFund.setScale(2, RoundingMode.HALF_UP);
        return AjaxResult.success(homePVO);
    }

    //根据项目类型分类
    @ApiOperation("根据项目类型分类")
    @GetMapping("/typePercentage")
    public AjaxResult typePercentage(){
        List<HomePVO> homePVOs = infoBaseProjectService.selecttypePercentage();
        return AjaxResult.success(homePVOs);
    }

    //每月项目数及金额综合
    @ApiOperation("每月项目数及金额综合")
    @GetMapping("/monthlySumAndTotal")
    public AjaxResult monthlySumAndTotal(HomePVO homePVO){
        String year = homePVO.getYear();
        List<HomePVO> homePVOS = infoBaseProjectService.selectmonthlySumAndTotal(year);
        return AjaxResult.success(homePVOS);
    }

    @GetMapping("/projectType")
    public AjaxResult projectType(HomePVO homePVO){
        List<HomePVO> homePVOS = infoBaseProjectService.selectprojectType(homePVO.getYear());
        return AjaxResult.success(homePVOS);
    }

}

